#coding:utf-8

import poplib,email
from email.header import decode_header
import smtplib
import time
import os,sys
import re

def accp_mail():
    host = "pop.163.com"
    username = "your email@163.com"
    password = "your password"
    pp = poplib.POP3(host)
    pp.set_debuglevel(1)
    pp.user(username)
    pp.pass_(password)
    ret = pp.stat()
    print ret
    ret = pp.list()
    print ret
    down = pp.retr(len(ret[1]))
    pat = re.compile(r"<(.*)>")
    a = down[1][10]
    pli = pat.search(a)
    b = down[1][12]
    #print pli.group(1)
    #print b
    #i = 1
    #for line in down[1]:
    #    print str(i) + ":" + line
    #    i = i + 1
    try:
        str1 = pli.group(1)
    except AttributeError:
        pass
    else: 
        if pli.group(1) != "youremail@foxmail.com":
            pass
        else:
            if b == "Subject: shutdown":
                return 0
    pp.quit()
    #b = down[1][33].decode('utf-8')

def send_mail1():
    mail_to = smtplib.SMTP('smtp.163.com',25)
    mail_to.login('your email@163.com','your password')
    msg = """From: likang <youremail@163.com>
To: 李康 <youremail@qq.com>
Subject: already shutdown
"""
    mail_to.sendmail('youremail@163.com','youremail@qq.com',msg)
    mail_to.close()

def send_mail2():
    
    mail_to = smtplib.SMTP('smtp.163.com',25)
    mail_to.login('youremail@163.com','yourpassword')
    msg = """From: likang <youremail@163.com>
To:  <youremail@163.com>
Subject: already shutdown
"""
    mail_to.sendmail('youremail@163.com','youremail@163.com',msg)
    mail_to.close()

if __name__ == '__main__':
    while 1:
        time.sleep(5)
        val = accp_mail()
        if val == 0:
            send_mail1()
            send_mail2()
            os.system("shutdown -P now")